//
//  LFTMCTeamCardViewController.m
//  lofter-mvpcourse-ios
//
//  Created by Thomas Quan on 2017/5/3.
//  Copyright © 2017年 undefined-zola. All rights reserved.
//

#import "LFTMCTeamCardViewController.h"
#import "NIMTeamCardRowItem.h"
#import "UIView+NIM.h"
#import "UIImage+NIM.h"
#import "NIMKitColorButtonCell.h"
#import "NIMAdvancedTeamMemberCell.h"
#import "UIView+Toast.h"
#import "NIMTeamMemberCardViewController.h"
#import "NIMCardMemberItem.h"
#import "NIMContactSelectViewController.h"
#import "NIMGroupedUsrInfo.h"
#import "NIMTeamMemberListViewController.h"
#import "NIMTeamAnnouncementListViewController.h"
#import "NIMKitUtil.h"
#import "NIMTeamSwitchTableViewCell.h"
#import "NIMAvatarImageView.h"
#import "SVProgressHUD.h"
#import "LFTMCUpdateTeamNameViewController.h"
#import "LFTMCTeamMemberCell.h"
#import <CommonCrypto/CommonDigest.h>
#import "LFTMCUtil.h"
#import "LFTMCWebViewController.h"
#import "UIButton+LFTMCBlock.h"

#pragma mark - Team Header View
#define CardHeaderHeight 190

@interface LFTMCIntroCourseLabel : UILabel

@property (nonatomic, assign) UIEdgeInsets textInsets;

@end

@implementation LFTMCIntroCourseLabel

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _textInsets = UIEdgeInsetsZero;
        
    }
    return self;
}

- (void)drawTextInRect:(CGRect)rect {
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, _textInsets)];
}

@end

@interface LFTMCMoreCourseIntroView : UIView

@property (nonatomic, strong) UIButton *moreBtn;

@property (nonatomic, strong) UIImageView *imageView;

@end

@implementation LFTMCMoreCourseIntroView

- (instancetype)init
{
    self = [super init];
    if (self) {
        _moreBtn = [[UIButton alloc] init];
        [_moreBtn setTitle:@"更多课程简介" forState:UIControlStateNormal];
        _moreBtn.titleLabel.font = [UIFont systemFontOfSize:14.f];
        [_moreBtn setTitleColor:NIMKit_UIColorFromRGB(0x999999) forState:UIControlStateNormal];
        [_moreBtn.titleLabel sizeToFit];
        [_moreBtn setUserInteractionEnabled:YES];
        [_moreBtn addTarget:self action:@selector(didClickMoreBtn) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_moreBtn];
        _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"LFTMC_More"]];
        [self addSubview:_imageView];
    }
    return self;
}


- (void)layoutSubviews {
    [super layoutSubviews];
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat height = 49.f;
    _moreBtn.nim_width = 90;
    _moreBtn.nim_height = 20;
    _moreBtn.nim_centerX = width / 2;
    _moreBtn.nim_centerY = height / 2;

    _imageView.nim_width = 7;
    _imageView.nim_height = 12;
    _imageView.nim_left = _moreBtn.nim_right + 5;
    _imageView.nim_centerY = height / 2;
}

- (UIViewController *)currentViewController {
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    UIViewController *vc = keyWindow.rootViewController;
    while (vc.presentedViewController) {
        vc = vc.presentedViewController;
        
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = [(UINavigationController *)vc visibleViewController];
        } else if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = [(UITabBarController *)vc selectedViewController];
        }
    }
    return vc;
}

- (void)didClickMoreBtn {
    NSString *url= [LFTMCUtil sharedInstance].teamModel.courseDetailURL;
    UIApplication *app = [UIApplication sharedApplication];
    if ([app canOpenURL:url]) {
        [[LFTMCUtil sharedInstance].dataSource lftmc_trackEventID:@"CourseIntroductionClick"
                                                         category:nil
                                                            label:nil
                                                       attributes:nil];
        UIViewController *vc = [self currentViewController];
        LFTMCWebViewController *webViewVC = [LFTMCWebViewController new];
        webViewVC.url = url;
        NIMTeam *team = [[NIMSDK sharedSDK].teamManager teamById:[LFTMCUtil sharedInstance].teamModel.teamId];
        webViewVC.title = team.teamName;
        webViewVC.userAgent = [LFTMCUtil sharedInstance].teamModel.userAgent;
        [vc.navigationController pushViewController:webViewVC animated:YES];
        
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"无法打开此链接"
                                                            message:nil
                                                           delegate:self
                                                  cancelButtonTitle:@"好"
                                                  otherButtonTitles:nil, nil];
        [alertView show];
    }
}

@end


@interface LFTMCTeamCardHeaderView : UIView

@property (nonatomic,strong) NIMTeam *team;

@property (nonatomic, strong) LFTMCIntroCourseLabel *introView;

@property (nonatomic, strong) UIView *lineView;

@property (nonatomic, strong) LFTMCMoreCourseIntroView *moreView;

@end

@implementation LFTMCTeamCardHeaderView

- (instancetype)initWithTeam:(NIMTeam*)team model:(LofterMvpCourseTeamModel *)model{
    self = [super initWithFrame:CGRectZero];
    if (self) {
        _team = [[NIMSDK sharedSDK].teamManager teamById:team.teamId];
        self.backgroundColor = NIMKit_UIColorFromRGB(0xecf1f5);
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        
        _introView = [[LFTMCIntroCourseLabel alloc] initWithFrame:CGRectZero];
        _introView.backgroundColor = [UIColor whiteColor];
        UIEdgeInsets edgeInsets = UIEdgeInsetsMake(20, 15, 20, 15);
        
//        _introView.text = model.courseDesc;
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:model.courseDesc];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:10];//调整行间距
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [model.courseDesc length])];
        _introView.attributedText = attributedString;
        _introView.numberOfLines = 2;
        _introView.textInsets = edgeInsets;
        _introView.font = [UIFont systemFontOfSize:16];
        _introView.textColor = NIMKit_UIColorFromRGB(0x333333);
        [self addSubview:_introView];
        
        _lineView = [[UIView alloc] initWithFrame:CGRectZero];
        _lineView.backgroundColor = NIMKit_UIColorFromRGB(0xEEEEEE);
        [self addSubview:_lineView];
        
        _moreView = [[LFTMCMoreCourseIntroView alloc] init];
        _moreView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_moreView];
        for (UIView *view in self.subviews) {
            [view setNeedsLayout];
        }
    }
    return self;
}

- (CGSize)sizeThatFits:(CGSize)size{
    return CGSizeMake(size.width, CardHeaderHeight);
}

#define AvatarLeft 20
#define AvatarTop  25
#define TitleAndAvatarSpacing 10
#define NumberAndTimeSpacing  10
#define MaxTitleLabelWidth 200
- (void)layoutSubviews{
    [super layoutSubviews];
    CGSize size = [UIScreen mainScreen].bounds.size;
    _introView.nim_width = size.width;
    _introView.nim_height = 100.f;
    _introView.nim_top = 20.f;
    _introView.nim_left = 0.f;
    
    _lineView.nim_height = 1.f;
    _lineView.nim_top = _introView.nim_bottom;
    _lineView.nim_width = size.width;
    _lineView.nim_left = 0.f;
    
    _moreView.nim_width = size.width;
    _moreView.nim_top = _lineView.nim_bottom;
    _moreView.nim_left = 0.f;
    _moreView.nim_height = 49.f;
}

- (UIViewController *)currentViewController {
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    UIViewController *vc = keyWindow.rootViewController;
    while (vc.presentedViewController) {
        vc = vc.presentedViewController;
        
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = [(UINavigationController *)vc visibleViewController];
        } else if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = [(UITabBarController *)vc selectedViewController];
        }
    }
    return vc;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSString *url= [LFTMCUtil sharedInstance].teamModel.courseDetailURL;
    UIApplication *app = [UIApplication sharedApplication];
    if ([app canOpenURL:url]) {
        [[LFTMCUtil sharedInstance].dataSource lftmc_trackEventID:@"CourseIntroductionClick"
                                                         category:nil
                                                            label:nil
                                                       attributes:nil];
        UIViewController *vc = [self currentViewController];
        LFTMCWebViewController *webViewVC = [LFTMCWebViewController new];
        webViewVC.url = url;
        webViewVC.title = _team.teamName;
        webViewVC.userAgent = [LFTMCUtil sharedInstance].teamModel.userAgent;
        [vc.navigationController pushViewController:webViewVC animated:YES];
        
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"无法打开此链接"
                                                            message:nil
                                                           delegate:self
                                                  cancelButtonTitle:@"好"
                                                  otherButtonTitles:nil, nil];
        [alertView show];
    }
}


@end

#pragma mark - Card VC
#define TableCellReuseId        @"tableCell"
#define TableButtonCellReuseId  @"tableButtonCell"
#define TableMemberCellReuseId  @"tableMemberCell"
#define TableSwitchReuseId      @"tableSwitchCell"

typedef NS_ENUM(NSInteger, LFTMCSwicherType) {
    LFTMCSwicherTypeOnlyTcher = 0,
    LFTMCSwicherTypeTeamMute = 1,
};

@interface LFTMCTeamCardViewController ()<NIMAdvancedTeamMemberCellActionDelegate,NIMContactSelectDelegate,NIMTeamSwitchProtocol,NIMTeamManagerDelegate,UIActionSheetDelegate,UITableViewDataSource,UITableViewDelegate,UINavigationControllerDelegate,UpdateTeamNameDelegate,
LFTMCTeamMemberCellActionDelegate>{
}

@property (nonatomic,strong) UITableView *tableView;

@property(nonatomic,strong) NIMTeam *team;

@property(nonatomic,strong) NIMTeamMember *myTeamInfo;

@property(nonatomic,copy) NSArray *bodyData;

@property(nonatomic,copy) NSArray *memberData;

@property(nonatomic,assign) BOOL isMuted;

@property (nonatomic, assign) LFTMCStatus teamStatus;

@end

@implementation LFTMCTeamCardViewController

- (instancetype)initWithTeam:(NIMTeam *)team AndTeamModel:(LofterMvpCourseTeamModel *)model{
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        _team = team;
    }
    return self;
}

- (void)dealloc
{
    [[NIMSDK sharedSDK].teamManager removeDelegate:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNav];
    self.isMuted = self.team.inAllMuteMode;
    self.teamStatus = [LFTMCUtil statusForTeamByModel:[LFTMCUtil sharedInstance].teamModel mutedMembers:nil];
    LFTMCTeamCardHeaderView *headerView = [[LFTMCTeamCardHeaderView alloc] initWithTeam:self.team model:[LFTMCUtil sharedInstance].teamModel];
    headerView.nim_size = [headerView sizeThatFits:self.view.nim_size];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = [LFTMCUtil titleMaker:self.team.teamName];
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.tableView];
    
    self.tableView.tableHeaderView = headerView;
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = NIMKit_UIColorFromRGB(0xecf1f5);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    __weak typeof(self) wself = self;
    [self requestData:^(NSError *error) {
        if (!error) {
            [wself reloadData];
        }
    }];
    
    [[NIMSDK sharedSDK].teamManager addDelegate:self];
}

- (void)close {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupNav {
    UIBarButtonItem *backButtonItem =
    [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"LFTMC_Back"]
                                     style:UIBarButtonItemStylePlain
                                    target:self
                                    action:@selector(close)];
    [backButtonItem setTintColor:NIMKit_UIColorFromRGB(0x333333)];
    self.navigationItem.leftBarButtonItem = backButtonItem;
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self reloadData];
    self.isMuted = self.team.inAllMuteMode;
}

- (void)reloadTeamDate {
    [self reloadData];
    self.isMuted = self.team.inAllMuteMode;
}

- (void)reloadData{
    self.myTeamInfo = [[NIMSDK sharedSDK].teamManager teamMember:self.myTeamInfo.userId inTeam:self.myTeamInfo.teamId];
    [self buildBodyData];
    [self.tableView reloadData];
    
    self.navigationItem.title  = [LFTMCUtil titleMaker:self.team.teamName];
}

- (void)requestData:(void(^)(NSError *error)) handler{
    __weak typeof(self) wself = self;
    [[NIMSDK sharedSDK].teamManager fetchTeamMembers:self.team.teamId completion:^(NSError *error, NSArray *members) {
        if (!error) {
            for (NIMTeamMember *member in members) {
                if ([member.userId isEqualToString:[NIMSDK sharedSDK].loginManager.currentAccount]) {
                    wself.myTeamInfo = member;
                    break;
                }
            }
            
            // 按照进群时间排序
            wself.memberData =
            [members sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                NIMTeamMember *member1 = obj1;
                NIMTeamMember *member2 = obj2;
                NSTimeInterval createTime1 = member1.createTime;
                NSTimeInterval createTime2 = member2.createTime;
                NSNumber *number1 = [NSNumber numberWithDouble:createTime1];
                NSNumber *number2 = [NSNumber numberWithDouble:createTime2];
                NSComparisonResult result = [number1 compare:number2];
                return result == NSOrderedDescending;
             }];
            
            
//            wself.memberData = members;
        }else if(error.code == NIMRemoteErrorCodeTeamNotMember){
            [wself.view makeToast:@"你已经不在群里" duration:2
                         position:CSToastPositionCenter];
        }else{
            [wself.view makeToast:@"群成员获取失败" duration:2
                         position:CSToastPositionCenter];
        }
        handler(error);
    }];
}

- (void)buildBodyData{
    BOOL canEdit = [NIMKitUtil canEditTeamInfo:self.myTeamInfo];
    BOOL isOwner    = self.myTeamInfo.type == NIMTeamMemberTypeOwner;
    BOOL isManager  = self.myTeamInfo.type == NIMTeamMemberTypeManager;
    
    NIMTeamCardRowItem *teamMember = [[NIMTeamCardRowItem alloc] init];
    teamMember.title  = @"群成员";
    teamMember.rowHeight = 150.f;
    teamMember.type   = TeamCardRowItemTypeTeamMember;
    teamMember.actionDisabled = YES;
    
    NIMTeamCardRowItem *teamName = [[NIMTeamCardRowItem alloc] init];
    teamName.title = @"群名称";
    teamName.subTitle = [LFTMCUtil titleMaker:self.team.teamName];
    teamName.action = @selector(updateTeamName);
    teamName.rowHeight = 60.f;
    teamName.type   = TeamCardRowItemTypeCommon;
    teamName.actionDisabled = !canEdit;
    
    NIMTeamCardRowItem *onlyTcher = [[NIMTeamCardRowItem alloc] init];
    onlyTcher.title = @"只看讲师";
    onlyTcher.switchOn = [LFTMCUtil shouldOnlySeeTeacherBySessionId:self.team.teamId];
    onlyTcher.tag = LFTMCSwicherTypeOnlyTcher;
    onlyTcher.rowHeight = 60.f;
    onlyTcher.type = TeamCardRowItemTypeSwitch;
    
    NIMTeamCardRowItem *teamMute = [[NIMTeamCardRowItem alloc] init];
    teamMute.title = @"群禁言";
    teamMute.switchOn = self.isMuted;
    teamMute.tag = LFTMCSwicherTypeTeamMute;
    teamMute.rowHeight = 60.f;
    teamMute.type = TeamCardRowItemTypeSwitch;
    
    NIMTeamCardRowItem *endCourse = [[NIMTeamCardRowItem alloc] init];
    endCourse.title  = @"结束课程";
    endCourse.rowHeight = 60.f;
    endCourse.action = @selector(endCourseAction);
    endCourse.type   = TeamCardRowItemTypeRedButton;
    if (_teamStatus == LFTMCStatusCourseEnded) {
        endCourse.actionDisabled = YES;
    } else {
        endCourse.actionDisabled = NO;
    }
    
    if (isOwner) {
        self.bodyData = @[
                          @[teamMember],
                          @[teamName],
                          @[onlyTcher, teamMute],
                          @[endCourse],
                          ];
    } else if (isManager) {
        self.bodyData = @[
                          @[teamMember],
                          @[teamName],
                          @[onlyTcher, teamMute],
                          ];
    } else{
        self.bodyData = @[
                          @[teamMember],
                          @[teamName],
                          @[onlyTcher],
                          ];
    }
}

- (id<NTESCardBodyData>)bodyDataAtIndexPath:(NSIndexPath*)indexpath{
    NSArray *sectionData = self.bodyData[indexpath.section];
    return sectionData[indexpath.row];
}

- (NSIndexPath *)cellIndexPathByTitle:(NSString *)title {
    __block NSInteger section = 0;
    __block NSInteger row = 0;
    [self.bodyData enumerateObjectsUsingBlock:^(NSArray *rows, NSUInteger s, BOOL *stop) {
        __block BOOL stopped = NO;
        [rows enumerateObjectsUsingBlock:^(NIMTeamCardRowItem *item, NSUInteger r, BOOL *stop) {
            if([item.title isEqualToString:title]) {
                section = s;
                row = r;
                *stop = YES;
                stopped = YES;
            }
        }];
        *stop = stopped;
    }];
    return [NSIndexPath indexPathForRow:row inSection:section];
}

#pragma mark - NIMTeamManagerDelegate
- (void)onTeamMemberChanged:(NIMTeam *)team
{
    __weak typeof(self) weakSelf = self;
    [self requestData:^(NSError *error) {
        [weakSelf reloadData];
    }];
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    id<NTESCardBodyData> bodyData = [self bodyDataAtIndexPath:indexPath];
    if ([bodyData respondsToSelector:@selector(actionDisabled)] && bodyData.actionDisabled) {
        return;
    }
    if ([bodyData respondsToSelector:@selector(action)]) {
        if (bodyData.action) {
            NIMKit_SuppressPerformSelectorLeakWarning([self performSelector:bodyData.action]);
        }
    }
}

#pragma mark - UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    id<NTESCardBodyData> bodyData = [self bodyDataAtIndexPath:indexPath];
    return bodyData.rowHeight;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.bodyData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *sectionData = self.bodyData[section];
    return sectionData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    id<NTESCardBodyData> bodyData = [self bodyDataAtIndexPath:indexPath];
    UITableViewCell * cell;
    NIMKitTeamCardRowItemType type = bodyData.type;
    switch (type) {
        case TeamCardRowItemTypeCommon:
            cell = [self builidCommonCell:bodyData];
            break;
        case TeamCardRowItemTypeRedButton:
            cell = [self builidRedButtonCell:bodyData];
            break;
        case TeamCardRowItemTypeTeamMember:
            cell = [self builidTeamMemberCell:bodyData];
            break;
        case TeamCardRowItemTypeSwitch:
            cell = [self buildTeamSwitchCell:bodyData];
            break;
        default:
            break;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.0f;
    }
    return 20.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    view.backgroundColor = NIMKit_UIColorFromRGB(0xecf1f5);
    return view;
}


- (UITableViewCell*)builidCommonCell:(id<NTESCardBodyData>) bodyData{
    UITableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:TableCellReuseId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:TableCellReuseId];
        CGFloat left = 15.f;
        UIView *sep = [[UIView alloc] initWithFrame:CGRectMake(left, cell.nim_height-1, cell.nim_width, 1.f)];
        sep.backgroundColor = NIMKit_UIColorFromRGB(0xebebeb);
        [cell addSubview:sep];
        sep.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    }
    cell.textLabel.text = bodyData.title;
    if (_myTeamInfo.type == NIMTeamTypeNormal) {
        cell.accessoryView = [UIView new];
    } else {
        cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"LFTMC_More"]];
    }
    
    if ([bodyData respondsToSelector:@selector(subTitle)]) {
        cell.detailTextLabel.text = bodyData.subTitle;
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
//    if ([bodyData respondsToSelector:@selector(actionDisabled)] && bodyData.actionDisabled) {
//        cell.accessoryType = UITableViewCellAccessoryNone;
//    }else{
//        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//    }
    return cell;
    
}

- (UITableViewCell*)builidRedButtonCell:(id<NTESCardBodyData>) bodyData{
    NIMKitColorButtonCell * cell = [self.tableView dequeueReusableCellWithIdentifier:TableButtonCellReuseId];
    if (!cell) {
        cell = [[NIMKitColorButtonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableButtonCellReuseId];
    }
    cell.status = _teamStatus;
    cell.button.style = NIMKitColorButtonCellStyleRed;
    if (_teamStatus != LFTMCStatusCourseEnded) {
        [cell.button setTitle:bodyData.title forState:UIControlStateNormal];
    } else {
        [cell.button setTitle:@"课程已结束" forState:UIControlStateNormal];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    return cell;
}

- (UITableViewCell*)builidTeamMemberCell:(id<NTESCardBodyData>) bodyData{
    LFTMCTeamMemberCell * cell = [self.tableView dequeueReusableCellWithIdentifier:TableMemberCellReuseId];
    if (!cell) {
        cell = [[LFTMCTeamMemberCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableMemberCellReuseId];
        cell.delegate = self;
    }
    [cell refreshWithTeam:self.team members:self.memberData width:self.tableView.nim_width];
//    cell.textLabel.text = bodyData.title;
//    cell.detailTextLabel.text = bodyData.subTitle;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    return cell;
}

- (UITableViewCell *)buildTeamSwitchCell:(id<NTESCardBodyData>)bodyData
{
    NIMTeamSwitchTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:TableSwitchReuseId];
    if (!cell) {
        cell = [[NIMTeamSwitchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"NIMTeamSwitchTableViewCell"];
    }
    cell.textLabel.text = bodyData.title;
    cell.switcher.on = bodyData.switchOn;
    cell.switchDelegate = self;
    cell.tag = bodyData.tag;
    cell.accessoryType = UITableViewCellAccessoryNone;
    return cell;
}

- (void)memberCardAction:(UIViewController *)vc{
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)onStateChanged:(UISwitch *)switcher on:(BOOL)on
{
    __weak typeof(self) weakSelf = self;
    if (switcher.superview.tag == LFTMCSwicherTypeOnlyTcher) {
        // 只看讲师
        [[LFTMCUtil sharedInstance].dataSource lftmc_trackEventID:@"ScanLecturer"
                                                         category:nil
                                                            label:on ? @"ON" : @"OFF"
                                                       attributes:nil];
//        NSLog(@"只看讲师");
        if ([self.delegate respondsToSelector:@selector(setOnlyTeacher:)]) {
            [self.delegate setOnlyTeacher:on];
        }

    } else if (switcher.superview.tag == LFTMCSwicherTypeTeamMute) {
        [[LFTMCUtil sharedInstance].dataSource lftmc_trackEventID:@"GroupGag"
                                                         category:nil
                                                            label:on ? @"ON" : @"OFF"
                                                       attributes:nil];
//        NSLog(@"群禁言");
        [[LFTMCUtil sharedInstance].dataSource lftmc_muteTeam:[LFTMCUtil sharedInstance].teamModel.teamId
                                   mute:on
                        completeHandler:^(BOOL succ) {
                            if (succ) {
                                self.isMuted = on;
                                NSString *hintText = on ? @"开启群禁言成功" : @"取消群禁言成功";
                                [self.view makeToast:hintText
                                            duration:2.0
                                            position:CSToastPositionBottom];
                                
                                
                                
                            } else {
                                NSString *hintText = on ? @"开启群禁言失败" : @"取消群禁言失败";
                                [self.view makeToast:hintText
                                            duration:2.0
                                            position:CSToastPositionBottom];
                            }
                        }];
        
    }
    
}

- (void)endCourseAction {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确定要关闭课程吗？"
                                                                     message:nil
                                                              preferredStyle:UIAlertControllerStyleAlert];
    
    dispatch_block_t closeCourseBlock = ^{
        [[LFTMCUtil sharedInstance].dataSource lftmc_closeTeam:[LFTMCUtil sharedInstance].teamModel.teamId
                         completeHandler:^(BOOL succ) {
                             if (succ) {
                                 [self.view makeToast:@"课程已关闭"
                                             duration:2.0
                                             position:CSToastPositionBottom];
                                 _teamStatus = LFTMCStatusCourseEnded;
                                 [self.tableView reloadData];
                             } else {
                                 [self.view makeToast:@"课程关闭失败"
                                             duration:2.0
                                             position:CSToastPositionBottom];
                             }
                         }];
    };
    
    UIAlertAction *close = [UIAlertAction actionWithTitle:@"关闭"
                                                   style:UIAlertActionStyleDefault
                                                 handler:^(UIAlertAction * _Nonnull action) {
                                                     
                                                     closeCourseBlock();
                                                     
                                                 }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alertVC addAction:close];
    [alertVC addAction:cancel];
    
    [self presentViewController:alertVC animated:YES completion:nil];
    
}

- (void)updateTeamName {
    [[LFTMCUtil sharedInstance].dataSource lftmc_trackEventID:@"GroupNameModify"
                                                     category:nil
                                                        label:nil
                                                   attributes:nil];
    LFTMCUpdateTeamNameViewController *vc = [[LFTMCUpdateTeamNameViewController alloc] init];
    vc.team = self.team;
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 旋转处理 (iOS7)

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    NSIndexPath *reloadIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[reloadIndexPath] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - 旋转处理 (iOS8 or above)
- (void)viewWillTransitionToSize:(CGSize)size
       withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        NSIndexPath *reloadIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView reloadRowsAtIndexPaths:@[reloadIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    } completion:nil];
}



@end
